package cn.nfwx.tv.widget.qpop;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

import cn.nfwx.tv.widget.AutoAdjustRecylerView;

/**
 * 左右两边模糊器
 * Created by dell on 2018/4/9.
 */
public class FadeRecyclewView extends RecyclerView {
    private static final String TAG = "FadeRecyclewView";
    private Paint paint;
    private int height;
    private int width;
    private int spanPixel = 100;
    private LinearGradient linearGradient;
    private PorterDuffXfermode xfermode;

    public FadeRecyclewView(Context context) {
        this(context, null);
    }

    public FadeRecyclewView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FadeRecyclewView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        init();
    }

    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        xfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
        paint.setXfermode(xfermode);
    }

    public void setSpanPixel(int spanPixel) {
        this.spanPixel = spanPixel;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        height = h;
        width = w;
        float spanFactor = spanPixel / (height / 2f);
        linearGradient = new LinearGradient(0, 0, width / 2, height / 2,
                new int[]{0x00000000, 0xff000000, 0xff000000}, new float[]{0, spanFactor, 1f}, Shader.TileMode.CLAMP);
        paint.setShader(linearGradient);
    }

    @Override
    public void draw(Canvas c) {
        int layoutId = c.saveLayer(0, 0, width, height, null, Canvas.ALL_SAVE_FLAG);
        super.draw(c);
        c.drawRect(0, 0, width, height, paint);
        c.restoreToCount(layoutId);
    }
}
